import { AfterViewInit, Component, OnInit, Renderer2 } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { deepClone } from '../../../utils/utils';
import { ApesMessageService } from '@shared/apes/message';
import { HttpClient } from '@angular/common/http';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { UserAuthService } from '@core/services/user-auth.service';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import { Events } from '@core/services/events/Events';
import { FormService } from '@core/services/form.service';

@Component({
  selector: 'service-order-flow',
  templateUrl: './vehicle-control.component.html',
  styleUrls: ['./vehicle-control.component.scss'],
})
export class VehicleControlComponent implements OnInit, AfterViewInit {

  carControlLoading: boolean = false;
  carControlTotal: any[] = [];
  carControlModel: any = {};
  carControlField: FormlyFieldConfig[] = [
    {
      key: 'deptId',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAllSearch',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 9,
        lblCol: 8,
        inputCol: 16,
      },
    },
  ];
  showCarControlItem: any[] = [];
  showCarMore: boolean = false;
  carMoreData: any;
  carControlItem: any[] = [];


  constructor(
    private apiService: ApiService,
    private msg: ApesMessageService,
    private http: HttpClient,
    private userService: UserAuthService,
    protected contextService: ApesContextMenuService,
    private renderer: Renderer2,
    protected events: Events,
    private formService: FormService,
  ) {
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.initCarControlData();
    this.refreshCarControlItem();


    this.events.subscribe(this.getUrl(), data => {
      if (this.carControlTotal.length != 0) {
        this.filterCarControlItem(this.carControlTotal, 0);
      }
    });
  }

  private getUrl(): string {
    let url = 'custom/vehicleControl/VehicleControlComponent';
    return url;
  }

  initCarControlData() {
    this.showCarMore = false;
    this.carControlModel = {};
    this.carControlTotal = [];
    this.carControlItem = [];
    this.showCarControlItem = [];
    this.clearCache();
  }

  clearCache() {
    if (this.formService.formData.hasOwnProperty('key')) {
      delete this.formService.formData['key'];
    }
  }

  refreshCarControlItem() {
    let deptId = this.checkDeptId();
    if (!deptId) return;
    this.carControlLoading = true;
    let api = 'fn.WorkDeskVehicleControlService.vehicleControlHomePage';
    let setData = { 'deptId': deptId }; //'6017R001'
    this.carControlTotal = [];
    this.carControlItem = [];
    this.showCarControlItem = [];
    this.apiService.post(api, setData).subscribe((data) => {
      console.log(data);
      this.carControlLoading = false;
      this.carControlTotal = data.totalData;
      this.carControlItem = data.cardAll;
      this.showCarControlItem = data.cardAll;
      setTimeout(() => {
        this.showCarControlItemHeight();
      }, 10);
    });
  }

  checkDeptId() {
    let deptId;
    if (this.carControlModel['deptId']) {
      deptId = this.carControlModel['deptId'];
    } else {
      let userAccount = this.userService.getUserInfoObj().userAccount;
      deptId = userAccount.post.dept ? userAccount.post.dept.id : null;
    }
    return deptId;
  }

  filterCarControlItem(params, index) {
    let param = params[index];
    let remark = param.remark;
    let items = deepClone(this.carControlItem);
    this.showCarControlItem = [];
    let activate = true;
    params.forEach((p) => {
      if (!p.hasOwnProperty('activate')) {
        p['activate'] = false;
      }
      if (p.remark != remark) {
        p.activate = false;
      } else {
        p.activate = !p.activate;
        activate = p.activate;
      }
    });

    if (activate) {
      items.forEach((item) => {
        let exp = item.STATE.indexOf('内协') != -1 ? '内协中' : item.STATE;
        if (exp == remark) {
          this.showCarControlItem.push(item);
        }
      });
    } else {
      this.showCarControlItem = items;
    }
    this.clearCache();

    setTimeout(() => {
      this.showCarControlItemHeight();
    }, 10);
  }

  checkCarState(state) {
    let color;
    switch (state) {
      case '在店':
        color = '#87d068';
        break;
      case '未结算交车':
        color = '#f50';
        break;
      case '待交车':
        color = '#2db7f5';
        break;
      case '内协中':
        color = '#722ed1';
        break;
      default:
        color = '#87d068';
        break;
    }
    return color;
  }

  carMoreBtn(param) {
    this.showCarMore = true;
    this.showCarControlItemHeight();
    this.carMoreData = deepClone(param);
  }

  checkCarShowData(car) {
    let show = true;
    if (car.hasOwnProperty('showData')) {
      show = car.showData;
    }
    return show;
  }

  checkCardImg(state) {
    let img;
    switch (state) {
      case 'FW':
        img = 'assets/tmp/img/home/crm.servicePlanItem.png';
        break;
      case 'DS':
        img = 'assets/tmp/img/home/fn.lossQuotation.png';
        break;
      default:
        img = 'pink';
        break;
    }
    return img;
  }

  checkCardState(state) {
    let color;
    switch (state) {
      case 'BLUE':
        color = 'blue';
        break;
      case 'GREEN':
        color = 'green';
        break;
      default:
        color = 'pink';
        break;
    }
    return color;
  }

  carShowMore(param) {
    if (param.hasOwnProperty('showData')) {
      param.showData = !param.showData;
    } else {
      param['showData'] = false;
    }
    if (param.showData) {
      setTimeout(() => {
        this.showCarControlItemHeight();
      }, 10);
      return;
    }
    let api = 'fn.WorkDeskVehicleControlService.vehicleControlCardDetail';
    this.apiService.post(api, param).subscribe((data) => {
      console.log(data);
      param['cardDetail'] = data.cardDetail;
      setTimeout(() => {
        this.showCarControlItemHeight();
      }, 10);
    });
  }

  checkCarMsg(msg) {
    let img;
    switch (msg) {
      case '你太棒了，此车业务已处理完毕，赶紧通知客户取车吧！':
        img = 'assets/tmp/img/home/000435.png';
        break;
      case 'DS':
        img = 'assets/tmp/img/home/000429.png';
        break;
      default:
        img = 'assets/tmp/img/home/000430.png';
        break;
    }
    return img;
  }

  openToBill(param) {
    let resultData = param;
    resultData['LICENSE_NUMBER'] = param['CAR_LICENSE'];
    let api = 'fn.workDeskConfig.workDeskByDKD';
    let formId = 'form/crm.servicePlanItem';
    let config = { 'OAInterface': false, 'api': api };
    this.contextService.openContextLink(resultData, formId, config);
  }

  closeCarMore(e) {
    this.showCarMore = false;
    this.showCarControlItemHeight();
  }

  showCarControlItemHeight() {
    let item = document.getElementsByClassName('assistant-carControl-item');
    if (item.length == 0) return;
    let columnCount = this.showCarMore ? 1 : 2;

    let hrr = [];
    for (let i = 0; i < item.length; i++) {
      let left;
      this.renderer.removeStyle(item[i], 'top');
      this.renderer.removeStyle(item[i], 'left');
      this.renderer.setStyle(item[i], 'position', 'absolute');
      this.renderer.setStyle(item[i], 'width', '50%');
      if (i < columnCount) {
        left = this.showCarMore ? '0px' : i % 2 == 0 ? '0px' : '50%';
        this.renderer.setStyle(item[i], 'top', '0px');
        this.renderer.setStyle(item[i], 'left', `${left}`);
        hrr.push(item[i].clientHeight);
      } else {
        let min = Math.min(...hrr);
        let index = hrr.indexOf(min);
        let top = min + 'px';
        left = this.showCarMore ? '0px' : index % 2 == 0 ? '0px' : '50%';
        this.renderer.setStyle(item[i], 'top', `${top}`);
        this.renderer.setStyle(item[i], 'left', `${left}`);
        hrr[index] += item[i].clientHeight;
      }
    }
  }
}

